// pages/uploading_img/uploading_img.js
const app = getApp()
var util = require("../../utils/utils.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    liveComment: "",
    texts: "至少10个字",
    min: 10,
    max: 24,
    showModalStatus: false,
    showUpload: true,
    page: 1,
    imageList: [],
    itemList: []
  },
  delimg: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  //字数限制  
  inputs: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);

    //最少字数限制
    if (len <= this.data.min)
      this.setData({})
    else if (len > this.data.min)
      this.setData({
        liveComment: value
      })

    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    this.setData({
      currentWordNumber: len //当前字数  
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "视频上传"
    })
    this.loadActInfo();
  },
  loadActInfo: function () {
    var that = this;
    wx.request({
      url: app.httpUrl + '/activity/tutor/queryOngoingActivity',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "get",
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data != null) {
            that.setData({
              activity: res.data.data
            })
            that.queryValidAttachList();
            that.queryActImageList();
            return;
          }
          wx.showModal({
            title: '提示',
            content: '近期没有正在进行中的活动',
            success: function (res) {
            }
          })
        }
      }
    })
  },
  queryValidAttachList: function () {
    var that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryValidAttachList',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        operatorId: this.data.activity.hmSignId,
        attachType: 'video',
        relationType: 'live'
      },
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data.length > 0) {
            that.setData({ imageList: res.data.data, showUpload: false})
          }
        }
      }
    })
  },
  delAttach: function (event) {
    var id = event.currentTarget.dataset.key;
    var that = this;

    wx.showModal({
      title: '删除视频',
      content: '确认删除此视频?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.httpUrl + '/activity/live/delActivityAttach',
            header: {
              'xcx-xtoken': app.globalData.openid,
              'content-type': 'application/json' // 默认值
            },
            method: "post",
            data: {
              id: id
            },
            success: (res) => {
              if (res.data.code == '000') {
                var imageList = that.data.imageList;
                for (var i in imageList) {
                  if (imageList[i].id == id) {
                    imageList.splice(i, 1);
                    break;
                  }
                }
                that.setData({ 
                  imageList: imageList,
                  showUpload: imageList.length == 0 ? true : false
                })
              }
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  wxChooseImage: function (e) {
    var that = this;
    var count = this.data.imageList;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        wx.showLoading({
          title: '上传中...',
        })
        that.uploadVideo(tempFilePath);
      }
    })
  },
  uploadVideo: function (tempFilePath) {
    var that = this
    wx.uploadFile({
      url: app.httpUrl + '/activity/live/addActivityAttch',
      filePath: tempFilePath,
      name: 'file',
      formData: {
        'activityId': that.data.activity.activityId,
        'attachType': 'video',
        'operatorId': that.data.activity.hmSignId
      },
      header: {
        'xcx-xtoken': app.globalData.openid,
        "content-type": "multipart/form-data"
      },
      success: function (res) {
        var model = JSON.parse(res.data);
        if (model.code == '000') {
          var imageList = that.data.imageList;
          imageList.push(model.data);
          that.setData({ 
            imageList: imageList, 
            showUpload: false,
            itemList: [],
            page: 1,
            isOver: false
          })
          that.queryActImageList();
          wx.hideLoading();
        }
      },
      fail: function (res) {
        wx.showToast({ title: "视频上传失败!", icon: 'none', duration: 6000 });
        wx.hideLoading();
      }
    })
  },
  uploadThumbImage: function(id, url) {
    var that = this
    wx.uploadFile({
      url: app.httpUrl + '/activity/live/uploadThumbImage',
      filePath: url,
      name: 'file',
      formData: {
        'activityId': that.data.activity.activityId,
        'attachId': id
      },
      header: {
        'xcx-xtoken': app.globalData.openid,
        "content-type": "multipart/form-data"
      },
      success: function (res) {
        console.log("--scuess");
        console.log(res);
      },
      fail: function (res) {
        console.log("---fail");
        console.log(res);
        wx.showToast({ title: "视频缩略图上传失败!", icon: 'none', duration: 6000 });
        wx.hideLoading();
      }
    })
  },
  addActivityLive: function () {
    var that = this;
    var liveComment = this.data.liveComment;
    if (liveComment.length < 10) {
      wx.showToast({
        title: '描述内容不少于10个字',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (this.data.imageList == 0) {
      wx.showToast({
        title: '请上传视频',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.request({
      url: app.httpUrl + '/activity/live/addActivityLive',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        liveComment: this.data.liveComment,
        liveType: 'video',
        activityId: this.data.activity.activityId,
        marineId: this.data.activity.marineIds,
        hmSignId: this.data.activity.hmSignId
      },
      success: (res) => {
        if (res.data.code == '000') {
          wx.showToast({ title: '提交成功！', icon: 'success', duration: 3000 });
          that.setData({
            liveComment: '',
            showUpload: true,
            imageList: []
          })
        } else {
          wx.showToast({ title: "提交失败!", icon: 'none', duration: 3000 });
        }
      }
    })
  },
  loadMore: function () {
    this.queryActImageList();
  },
  queryActImageList: function () {
    // 活动图片
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryMyResource',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        hmSignId: this.data.activity.hmSignId,
        page: that.data.page,
        rows: 4,
        liveType: "video",
      },
      method: "POST",
      success: (res) => {
        if (that.data.page >= res.data.data.totalPage) {
          that.setData({
            isOver: true
          })
        }
        that.data.page += 1;
        var itemList = that.data.itemList;
        var list = res.data.data.results;
        for (var i in list) {
          for (var j in list[i].attachList) {
            if (j == 0) {
              list[i].firstVideoUrl = app.imgUrl + list[i].attachList[j].attachUrl;
              list[i].firstThumbUrl = app.imgUrl + list[i].attachList[j].thumbAttachUrl;
            }
          }
          itemList.push(list[i]);
        }
        that.setData({
          itemList: itemList
        })
      }
    })
  },
  delActivityLive: function (event) {
    var id = event.currentTarget.dataset.key;
    var that = this;
    wx.showModal({
      title: '删除视频',
      content: '确认删除次视频?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.httpUrl + '/activity/live/delActivityLive',
            header: {
              'xcx-xtoken': app.globalData.openid,
              'content-type': 'application/json' // 默认值
            },
            method: "post",
            data: {
              id: id
            },
            success: (res) => {
              if (res.data.code == '000') {
                var itemList = that.data.itemList;
                for (var i in itemList) {
                  if (itemList[i].id == id) {
                    itemList.splice(i, 1);
                    break;
                  }
                }
                if (res.data.data != null) {
                  that.setData({ itemList: itemList })
                }
              }
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  playVideo(e) {
    let index = e.currentTarget.dataset.index;
    let list = this.data.itemList;
    list.forEach(n => {
      n.isPlaying = false;
    })
    list[index].isPlaying = true;
    this.setData({
      itemList: list
    })
    let videoContext = wx.createVideoContext('video-' + index)
    videoContext.play()
  }
})